package postgres

import (
	"auth/model"
	"auth/model/entity"
)

var Role = &role{}

type role struct{}

func (a *role) Create(m *entity.Role) (int64, error) {
	err := db.Create(m).Error
	return m.ID, err
}

func (a *role) Find(id int64) (*entity.Role, error) {
	e := &entity.Role{}
	err := db.Model(&entity.Role{}).Find(&e, id).Error
	return e, err
}

func (a *role) Update(id int64, dict map[string]interface{}) error {
	return db.Model(&entity.Role{}).Where("id = ?", id).Updates(dict).Error
}

func (a *role) Delete(id int64) error {
	return db.Delete(&entity.Role{}, id).Error
}

func (a *role) List(in *model.RoleListRequest) (int, []*entity.Role, error) {
	var (
		q     = db.Model(&entity.Role{})
		err   error
		total int64
		roles []*entity.Role
	)

	if err = q.Count(&total).Error; err != nil {
		return 0, nil, err
	}
	if err = q.Limit(in.Size).Offset((in.Index - 1) * in.Size).Find(&roles).Error; err != nil {
		return 0, nil, err
	}
	return int(total), roles, nil
}
